// pages/settled/settled.js
//获取应用实例
var app = getApp();

Page({

  /**
   * 页面的初始数据
   */
  data: {
    loading: true,
    code:'aaa',//验证码是否正确
    count: 60,
    checked:false,//规则
    id:2,
    cartbox:false,
    model: [],//默认车辆
    models: []
    ,//默认车辆
    list:[
      {
        isFlag:0,
        length:"aaa",
        license:"aaa",//车牌号 ,
        payload:"aaa",//载量 ,
		uploadFile:"aaa",//车辆照片 ,
        vehicleType:"aaa",//车辆类型 ,
        vlicensePic:"aaa",//行驶证
        volume:"aaa"//体积
      }
    ],//真实车辆信息
    lists: 
      {
        isFlag: 0,
        length: "aaa",//车长
        license: "aaa",//车牌号 ,
        payload: "aaa",//载量 ,
        vehiclePic: "aaa",//车辆照片 ,
        vehicleType: "aaa",//车辆类型 ,
        vlicensePic: "aaa",//行驶证
        volume: "aaa"//体积
      }
    ,//模拟车辆信息
    city1:'请选择常用接货地址',//接货地址
    city2:'请选择常用送货地址',//送货地址
    
    //最终上传的身份证
    idimgs:'',
    //最终上传的驾驶证
    userimgs:'',
    status:'aaa',
    defaultUnitIndex: 0,      // 默认重量单位
    unitData: ['吨', '40寸集装箱', '20寸集装箱'],  // 模拟数据
    defaultUnit: ''
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this;

    that.setData({
      options:options,
      defaultUnit: this.data.unitData[this.data.defaultUnitIndex] // 页面初始化的时候初始化单位数据
    });

    //是否已经提交审核信息
    app.getLoginSession(function (session) {
        wx.request({
          url: app.api + '/wx_log_test/user/apporve?token=a'+session,
          success:function(event){
            var res = event.data;
            // 没入驻
            if (res.status == 400){
              that.setData({
                loading: false,
              })
              return false;
            }
            if(res.msg=="OK"){
              var data = res.data;
              console.log(event);
              that.setData({
                loading: false,
                status: data.driver.status
              })
              if (data.driver.status !=0) {//审核失败或者通过，把审核信息赋值回去
                if(data.driver.status == 1){
                  wx.setNavigationBarTitle({
                    title: '入驻信息',
                  })  
                }
                that.setData({
                  name: data.driver.driverName,
                  city1: data.driver.address1,
                  city2: data.driver.address2,
                  phone: data.driver.phone,
                  idnum: data.driver.idNo,
                  idimgs: data.driver.idpicA,
                  userimgs: data.driver.licensePic,
                  approvedInfo: data.driver.approvedInfo,
                  code:true
                })
                if(data.list.length>0){
                  that.setData({
                    list: data.list,
                  })
                }
                for (var i = 0; i < data.list.length; i++) {
                  if (data.list[i].isFlag == 1) {
                    that.setData({
                      cartbox: true
                    })
                  }
                }
              } else if (data.driver.status == 1) {
                wx.setNavigationBarTitle({
                  title: '入驻信息',
                })
              }
              var model = that.data.model;
              var models = that.data.models;
              for (var i = 1; i < data.list.length; i++) {
                model.push(models);
                console.log()
                that.setData({
                  model: model
                })
              }
              console.log(that.data.model);
            }else{
              that.setData({
                loading: false,
              })
              wx.showModal({
                title: '提示',
                content: '接口请求返回失败：' + event.statusCode + '返回内容：' + event.data,
              })
            }
          },
          fail:function(res){
          }
      })
    })
    that.cart_type();
  },


  // 单位选择器改变事件
  unitPickerChange: function (e) {
    this.setData({
      defaultUnit: this.data.unitData[e.detail.value]
    });
  },


  //添加车辆
  actcart:function(){
    var that = this;
    var list = that.data.list;
    var lists = that.data.lists;
    var model = that.data.model;
    var models = that.data.models;
    list.push(lists);
    model.push(models);
    that.setData({
      list:list,
      model: model
    })
    console.log(that.data.model);
  },
  //删除车辆
  delete:function(res){
  var that = this;
  var num = parseInt(res.currentTarget.dataset.num);
  console.log(num);
  var list = that.data.list;
  var model = that.data.model;
  list.splice(num,1);
  model.splice(num,1);
  console.log(list);
  that.setData({
    list:list,
    model: model
  })
  console.log(that.data.list);
  console.log(that.data.model);
  },
  switch:function(e){
    console.log(e);
    wx.navigateTo({
      url: '/pages/switchcity/switchcity?id='+e.currentTarget.dataset.id,
    })
  },
  // 实时获取用户输入
  input: function (event) {
    var that = this;
    var value = event.detail.value;
    var type = event.currentTarget.dataset.type;
    if (type == 'name') {
      this.setData({
        'name': value
      })
    } else if (type == 'phone') {
      this.setData({
        phone: value
      })
    } else if (type == 'idnum') {
      this.setData({
        idnum: value
      })
    } 
  },
  //获得车牌号
  cartinput:function(res){
    var that = this;
    console.log(res);
    var value = res.detail.value;
    var num = parseInt(res.currentTarget.dataset.num);
    that.data.list[num].license=value;
    that.setData({
      list:that.data.list
    })
  },
  //获得车长
  lengthinput: function (res) {
    var that = this;
    console.log(res);
    var value = res.detail.value;
    var num = parseInt(res.currentTarget.dataset.num);
    that.data.list[num].length = value;
    that.setData({
      list: that.data.list
    })

  },
  //获得体积
  volumeinput: function (res) {
    var that = this;
    console.log(res);
    var value = res.detail.value;
    var num = parseInt(res.currentTarget.dataset.num);
    that.data.list[num].volume = value;
    that.setData({
      list: that.data.list
    })
  },
  //获得车长
  payloadinput: function (res) {
    var that = this;
    console.log(res);
    var value = res.detail.value;
    var num = parseInt(res.currentTarget.dataset.num);
    that.data.list[num].payload = value;
    that.setData({
      list: that.data.list
    })
  },
  // 验证码验证
  inputcode:function(res){
    var that = this;
    var value = res.detail.value;
    console.log(value + "aaaa" + that.data.code_num);

    app.getLoginSession(function (session) {
      wx.request({
        url: app.api + '/wx_log_test/user/checkbind',
        data: {
          phone: that.data.phone,
          code: value,
          token:session
        },
        success:function(res){
          var res = res.data;
          if(res.data=="false"){
            that.setData({
              code: false
            })
          }else{
            that.setData({
              code: true
            })
          }
        },
        fail:function(res){
          that.tips('验证码接口请求错误');
          return false;
        }
      })
    })
  },
  // 用户输入验证
  virifi: function () {
    var that = this;
    var error = '';
    var options = that.data.options;

    if (!that.data.name || that.data.name == '') {
      that.tips('请输入驾驶人');
      return false;
    } else if (!that.data.phone || that.data.phone == '' || !/^1[34578][0-9]{9}$/.test(that.data.phone)) {
      that.tips('请输入正确的手机号码');
      return false;
    } else if (that.data.code!=true) {
      that.tips('请输入正确的验证码');
      return false;
    } else if (!that.data.idnum || that.data.idnum == '' || !/(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/.test(that.data.idnum)) {
      that.tips('请输入正确的身份证号');
      return false;
    } else if (that.data.city1 == '请选择常用接货地址') {
      that.tips('请选择常用接货地址');
      return false;
    } else if (that.data.city2 == '请选择常用送货地址') {
      that.tips('请选择常用送货地址');
      return false;
    } else if (that.data.idimgs=='') {
      that.tips('请选择上传身份证照');
      return false;
    } else if (that.data.userimgs=='') {
      that.tips('请选择上传驾驶证');
      return false;
    }
    for(var i=0;i<that.data.list.length;i++){
      if (that.data.list[i].license == "aaa" || !/^[京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领A-Z]{1}[A-Z]{1}[A-Z0-9]{4}[A-Z0-9挂学警港澳]{1}$/.test(that.data.list[i].license)) {
        that.tips('请输入序号' + (i + 1) + '正确的车牌号');
        return false;
      }else if (that.data.list[i].vehicleType=="aaa"){
        that.tips('请选择序号' + (i + 1)+'车型');
        return false;
      } else if (that.data.list[i].length == "aaa" || that.data.list[i].length =='' ||!/^\d+(\.\d+)?$/.test(that.data.list[i].length )) {
        that.tips('请输入序号' + (i + 1) + '车长');
        return false;
      } else if (that.data.list[i].volume == "aaa" || that.data.list[i].volume == '' || !/^\d+(\.\d+)?$/.test(that.data.list[i].volume)) {
        that.tips('请输入序号' + (i + 1) + '体积');
        return false;
      } else if (that.data.list[i].payload == "aaa" || that.data.list[i].payload == '' || !/^\d+(\.\d+)?$/.test(that.data.list[i].payload)) {
        that.tips('请输入序号' + (i + 1) + '载重');
        return false;
      }else if (that.data.list[i].vlicensePic == "aaa") {
        that.tips('请上传序号' + (i + 1) + '行驶证图片');
        return false;
      } else if (that.data.list[i].vehiclePic == "aaa") {
        that.tips('请上传序号' + (i + 1) + '车辆图片');
        return false;
      } else if (that.data.cartbox == false) {
        that.tips('请选择默认车辆');
        return false;
      } else if (that.data.checked == false) {
        that.tips('请阅读《司机缴纳保证金》规则');
        return false;
      }
    }
    return true;
  },
  checkboxChange: function () {
    var that = this;
    that.setData({
      checked: that.data.checked==false?true:false
    })
  },
  // 上传图片
  uploadImg: function (img, storage, fn) {
    var that = this;
    var imgs = that.data.imgs;
    app.getLoginSession(function (session) {
      wx.uploadFile({
        url: app.api +'/wx_log_test/image/upload',
        filePath: img,
        name: 'file',
        formData: {
          file: img,
          token: session
        },
        method: 'POST',
        header: {
          'content-type': 'multipart/form-data'
        },
        success: function (res) {
          var rea = res.data;
          var data = JSON.parse(res.data);
          console.log(data);
          if (data.msg=="OK") {
              that.setData({
                [storage]: data.data
              })
              typeof fn == 'function' && fn();
          } else {
            that.tips('图片上传失败')
          }
        },
        fail: function () {
          console.log("失败");
        }
      })
    })
  },
  // 选择图片
  chooseImg: function (e) {
    var that = this;
    console.log(e)
    var img = e.currentTarget.dataset.img;
      wx.chooseImage({
        count: 1,
        sizeType: ['original', 'compressed'],
        sourceType: ['album', 'camera'],
        success: function (res) {
          console.log(res);
          var tempFilePaths = res.tempFilePaths
          for (var i = 0; i < tempFilePaths.length; i++) {
            that.uploadImg(tempFilePaths[i], img, function () {
            })
          }
        },
        fail: function () {
          that.tips('选取图片失败')
        }
      })
  },
  submit: function () {
    var that = this; 
    if(that.virifi()) {
      app.getLoginSession(function (session) {
        wx.request({
          url: app.api + '/wx_log_test/driver?token=' + session,
          data: {
            driver: {
              driverName: that.data.name,
              address1: that.data.city1,
              address2: that.data.city2,
              phone: that.data.phone,
              idNo: that.data.idnum,
              idpicA: that.data.idimgs,
              licensePic: that.data.userimgs,
              licenseType:'',
            },
            list: that.data.list
          },
          method: 'POST',
          header: {
            'content-type': 'application/json'
          },
          success: function (e) {
            var data = e.data;
            console.log(e);
            if(data.status!=500){
              if (data.data = "Success") {
                that.setData({
                  status: 0
                })
                console.log(data.data);
              } else {
                that.tips('信息提交失败')
              }
            }else{
              that.tips('接口连接错误')
            }
          }, fail: function () {
            that.tips('接口请求错误')
          }
        })
      })
    }
  },
  // 提示框
  tips: function (txt) {
    wx.showModal({
      title: '提示',
      content: txt,
      showCancel: false
    })
  },

  //车型
  modelChange: function (e) {
    var that = this;
    var num = parseInt(e.currentTarget.dataset.num)
    var choose = parseInt(e.detail.value);
    console.log(num);
    that.data.list[num].vehicleType = that.data.model[choose]
    that.setData({
      list:that.data.list
    })
    console.log(that.data.list);
  },
  //设置默认车辆
 control:function(res){
   var that = this;
   var num = parseInt(res.currentTarget.dataset.num);
   for(var i = 0;i<that.data.list.length;i++){
     if(i==num){
       that.data.list[i].isFlag = 1;
       that.setData({
         list: that.data.list,
         cartbox:true
       })
       console.log(that.data.list);
     }else{
       that.data.list[i].isFlag = 0;
       that.setData({
         list: that.data.list
       })
     }
   }
   
 },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
   var that= this;
   if (app.globalData.city1!=''){
     that.setData({
       city1: app.globalData.city1
     })
   }
   if(app.globalData.city2!=''){
     that.setData({
       city2: app.globalData.city2
     })
   }
  },
  //发送验证码
  getValidCode: function () {
    var that = this;
    if (that.data.phone && that.data.count == 60) {
      that.tick()
      app.getLoginSession(function (session) {
        wx.request({
          url: app.api + '/wx_log_test/user/getsix',
          data: {
            phone: that.data.phone,
            token:session
          },
          success:function(res){
            var res = res.data;
            if(res.msg!="OK"){
              that.tips('验证码发送失败，稍后重试！');
              return false;
            }else{
              that.setData({
                code_num:res.data.code
              })
              console.log(that.data.code_num);
            }
          }
        })
      })
    } else if (!that.data.phone) {
      wx.showToast({
        title: '请填写手机号码',
        icon: 'loading',
        duration: 1000
      })
    }
  },
  tick: function () {
    var vm = this
    if (vm.data.count > 0) {
      vm.setData({
        count: vm.data.count - 1
      });
      setTimeout(function () {
        return vm.tick()
      }, 1000)
    } else {
      vm.setData({
        count: 60
      });
    }
  },
  //獲取車型
  cart_type:function(res){
    var that = this;

    app.getLoginSession(function (session) {
      wx.request({
        url: app.api + "/wx_log_test/sys/vehicle?token="+session,
        success: function (res) {
          var model = that.data.model;
          var models = that.data.models;
          for(var i = 0;i<res.data.data.length;i++){
            model.push(res.data.data[i].value);
            that.setData({
              model:model,
              models:model
            })
          }
        }
      })
    })
  },
  iWantEditInfo :function(){
    this.setData({
      status: "iWantEditInfo"
    })
  }
})